import React, { useEffect } from 'react';
import { Form, Input, Radio, InputNumber } from 'antd';

import type { WrappedComponentProps } from "@yaf/pro-ui";

import { EnumVisibleTypeList } from '../../constants';
import { RespDataType, createMenu, updateMenu } from '../../../api';
import { EnumMenuType } from "../../constants";

interface CreateOrEditProps extends WrappedComponentProps {
  menuId?: number;
  optType: "add" | "edit";
  fetchList: () => void;
  editData?: RespDataType.MenuItem
}

const CreateOrEdit: React.FC<CreateOrEditProps> = ({ modalControl, optType, menuId, fetchList, editData }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    modalControl.registerOk(handleSubmit);
  });

  const handleSubmit = () => {
    form.validateFields().then((values) => {
      const success = () => {
        fetchList();
        modalControl.close()
      }
      const error = () => modalControl.hideSaving();

      if (optType == "edit") {
        values.parentId = editData.pid;
        updateMenu(menuId, values).then(success).catch(error)
      } else {
        values.parentId = menuId ? menuId : 0;
        createMenu(values).then(success).catch(error)
      }
    }).catch(() => modalControl.hideSaving())
  }

  return <Form
    form={form}
    initialValues={{
      menuSort:0,
      isHide:EnumVisibleTypeList[0].value,
      menuType:EnumMenuType[0].value,
      menuName: editData?.title ?? "",
      isLink: 0,
      isIframe: 0,
      ...editData
    }}
    labelCol={{ span: 6 }}
    wrapperCol={{ span: 16 }}
  >
    <Form.Item
      label="菜单名称"
      name="menuName"
      rules={[{ required: true, message: '菜单名称不能为空' }]}
    >
      <Input placeholder="请输入菜单名称" />
    </Form.Item>

    <Form.Item
      label="菜单类型"
      name="menuType"
      rules={[{ required: true, message: '菜单类型不能为空' }]}
    >
      <Radio.Group options={EnumMenuType}/>
    </Form.Item>

    <Form.Item
      label="路由路径"
      name="path"
      rules={[{ required: true, message: '路由路径不能为空' }]}
    >
      <Input placeholder="请输入路由路径" />
    </Form.Item>

    <Form.Item
      label="接口规则"
      name="name"
      rules={[{ required: true, message: '接口规则不能为空' }]}
    >
      <Input placeholder="请输入接口规则" />
    </Form.Item>

    <Form.Item
      label="菜单排序"
      name="menuSort"
    >
      <InputNumber style={{width: "100%"}} min={0} />
    </Form.Item>

    <Form.Item label="是否隐藏"name="isHide">
      <Radio.Group options={EnumVisibleTypeList}/>
    </Form.Item>

    <Form.Item label="链接地址"name="linkUrl">
      <Input />
    </Form.Item>
    <Form.Item label="是否外链"name="isLink">
      <Radio.Group options={[
        {label: "是",value: 1},
        {label: "否",value: 0},
      ]} />
    </Form.Item>

    <Form.Item label="是否内嵌"name="isIframe">
      <Radio.Group options={[
        {label: "是",value: 1},
        {label: "否",value: 0},
      ]} />
    </Form.Item>
  </Form>
}

export default CreateOrEdit

